package com.tianliang.springboottest.utils;

import com.tianliang.springboottest.Service.TaskMethod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.transaction.support.TransactionTemplate;

import java.util.ArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadPoolExecutor;

@Component
public class RunnableTransactionManager {

    @Autowired
    TransactionTemplate transactionTemplate;

    @Autowired
    PlatformTransactionManager transactionManager;

    @Autowired
    ThreadPoolExecutor executor;

    private Boolean isCommit = true;

    public void task(ArrayList<TaskMethod> tasks) {

        ArrayList<Runnable> runnables = new ArrayList<>();
        CountDownLatch count = new CountDownLatch(tasks.size());
        CountDownLatch sonCount = new CountDownLatch(1);
        for (TaskMethod taskMethod : tasks) {
            runnables.add(new Runnable() {

                @Override
                public void run() {
                    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
                    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
                    TransactionStatus status = transactionManager.getTransaction(def);
                    try {
                        taskMethod.task();
                        System.out.println("函数执行成功");
                        if (!(1 != 1 || isCommit == false)) {
                            isCommit = true;
                        }
                        count.countDown();
                        sonCount.await();
                        if (isCommit == true) {
                            transactionManager.commit(status);

                        } else {
                            transactionManager.rollback(status);
                        }
                    } catch (Exception e) {
                        isCommit = false;
                        transactionManager.rollback(status);
                        count.countDown();
                    }

                }
            });
        }

        try {
            for (Runnable runnable : runnables) {
                executor.execute(runnable);
            }
            count.await();
            sonCount.countDown();
        } catch (Exception e) {
            isCommit = false;
            System.out.println(e.getMessage());
        }
    }
}
